import { ref, onMounted, watch, toRefs } from 'vue'
import { useStore } from 'vuex'
import { UserInfoType } from '../types/common'
import { RESPONSE_STATUS } from '../constant/enum'
import MD5 from 'js-md5'
import { ToastUtil } from '../utils/vantUtils'
import { useRouter } from 'vue-router'

type UserOperateType = {
  login: Function,
  register: Function
}

export default function (state: UserInfoType): any {
  const token = ref('')
  const store = useStore()
  const router = useRouter()
  const operationType = ref('login')

  const userOperate: UserOperateType = {
    login: (userName: string, password: string): void => login(userName, password),
    register: (userName: string, password: string) => register(userName, password)
  }
  const onSubmit = async () => {
    const { userName, password } = state
    userOperate[operationType.value as keyof typeof userOperate](userName, password)
  }

  const switchOperationType = (): void => {
    const operationTypeMap: Map<string, string> = new Map()
    operationTypeMap.set('login', 'register')
    operationTypeMap.set('register', 'login')
    operationType.value = operationTypeMap.get(operationType.value) || operationType.value
  }

  const login = (userName: string|null, password: string|Number): void => {
    console.log('userName', userName)
    store.dispatch({
      type: 'asyncLogin',
      payload: {
        loginName: userName,
        passwordMd5: MD5(password.toString())
      }
    }).then((res: any):void => {
      if (res.resultCode === RESPONSE_STATUS.SUCCESS) {
        token.value = res.data
        store.commit('updateToken', {token: token.value})
        store.commit('updateUserInfo', {
          userName,
          password: MD5(password.toString())
        })
        router.push('/home')
      } else {
        ToastUtil.fail('登录失败')
      }
    }).catch((error: any): void => {
      console.error('dispatch asyncLogin occurs error, the error message is:', error)
      ToastUtil.fail('登录失败')
    })
  }

  const register = (userName: string, password: string) => {
    store.dispatch({
      type: 'asyncRegister',
      payload: {
        loginName: userName,
        password: password.toString()
      }
    }).then((res: any): void => {
      if (res.resultCode === RESPONSE_STATUS.SUCCESS) {
        ToastUtil.success('注册成功！')
        operationType.value = 'login'
      } else {
        ToastUtil.fail('注册失败')
        operationType.value = 'register'
      }
    }).catch((error: any): void => {
      console.error('dispatch asyncRegister occurs error, the error message is:', error)
      ToastUtil.fail('注册失败')
    })
  }

  return {
    operationType,
    switchOperationType,
    onSubmit
  }
}